# frozen_string_literal: true

require 'dotenv'
require 'json'

fastlane_version '2.0'

default_platform :mac

PROJECT_ROOT_FOLDER = File.dirname(File.expand_path(__dir__))

ENV_FILE_NAME = 'wordpress-desktop.env'
USER_ENV_FILE_PATH = File.join(Dir.home, '.a8c-apps', ENV_FILE_NAME)

TEAM_ID = 'PZYM8XX95Q'

CODE_SIGNING_STORAGE_OPTIONS = {
  storage_mode: 's3',
  s3_bucket: 'a8c-fastlane-match',
  s3_region: 'us-east-2'
}.freeze

# Required for sync_code_signing to authenticate with S3.
CODE_SIGNING_ENV_VARS = %w[
  MATCH_S3_ACCESS_KEY
  MATCH_S3_SECRET_ACCESS_KEY
  MATCH_PASSWORD
].freeze

# Required for app_store_connect_api_key to generate the key information to pass down the call chain.
ASC_API_KEY_ENV_VARS = %w[
  APP_STORE_CONNECT_API_KEY_KEY_ID
  APP_STORE_CONNECT_API_KEY_ISSUER_ID
  APP_STORE_CONNECT_API_KEY_KEY
].freeze

import 'lib/helpers.rb'

before_all do
  # This is necessary for 'match' to work correctly in CI. When running
  # locally, it has no effect so it's safe to run it before all lanes.
  setup_ci

  Dotenv.load(USER_ENV_FILE_PATH)
end

platform :mac do
  desc 'Download and configure code signing certificates and provisioning profiles .'
  lane :configure_code_signing do |readonly: true|
    require_env_vars!(*CODE_SIGNING_ENV_VARS)

    unless readonly
      # We need the API key instantiated only when making changes on ASC (readonly = false)
      require_env_vars!(*ASC_API_KEY_ENV_VARS)
      api_key = app_store_connect_api_key
    end

    sync_code_signing(
      type: 'developer_id',
      platform: 'macos',
      team_id: TEAM_ID,
      api_key: api_key,
      # Empty because we only care about the certificate at the moment, no need for provisioning profiles
      app_identifier: [],
      readonly: readonly,
      **CODE_SIGNING_STORAGE_OPTIONS
    )
  end
end
